package com.lyf.network.learn.nio.buffer;

import org.junit.Test;

import java.nio.Buffer;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.util.Random;

/**
 * @AUTHOR LYF
 * @DATE 2022/6/10
 * @VERSION 1.0
 * @DESC
 *
 * 1.创建分配
 * allocate,wrap
 *
 * 2.三属性设置
 * position,limit,capacity
 *
 * 3.数据处理
 * flip,rewind,clear,compact
 *
 * 4.数据读写
 * put,get
 *
 * 5.四大
 * （1）缓冲区分片
 */
public class BufferCommonApi {
    /**
     * ...API略
     */

    /**
     * 测试缓存区分片--主要理解三属性;子buffer共享--
     */
    @Test
    public void test1(){
        ByteBuffer buffer = ByteBuffer.allocate(10);

        // 先将buffer放值
        int i=1;
        while(buffer.hasRemaining()){
            buffer.put((byte) i++);//(byte) new Random().nextInt(10)
        }

        buffer.position(0);
        while (buffer.hasRemaining()){
            System.out.println(buffer.get());
        }

        //将position放置 3
        buffer.position(3);
        buffer.limit(7);
        ByteBuffer subBuffer = buffer.slice();

        while (subBuffer.hasRemaining()){
            subBuffer.put((byte)i++);
        }
//        for (int j=0;j<subBuffer.capacity();j++){
//
//        }

        buffer.position(0);
        buffer.limit(buffer.capacity());
        while (buffer.hasRemaining()){
            System.out.println(buffer.get());//(char)
        }
        //

    }

    /**
     * 测试只读缓冲区
     */
    @Test
    public void test2(){
        ByteBuffer buffer = ByteBuffer.allocate(10);
        ByteBuffer byteBuffer = buffer.asReadOnlyBuffer();

        // 直接缓存区，加快--读取速度
        ByteBuffer.allocateDirect(10);
        //new FileChannel().map(FileChannel.MapMode.PRIVATE,0,1);
//        FileChannel.MapMode.READ_WRITE
    }



}
